package com.yang.core.interceptor;

import com.yang.core.api.RestClientInterceptor;
import com.yang.core.model.RequestContext;
import com.yang.core.model.ResponseContext;
import com.yang.core.model.ExceptionContext;
import lombok.extern.slf4j.Slf4j;

/**
 * 日志拦截器
 * 开箱即用的功能
 */
@Slf4j
public class LoggingInterceptor implements RestClientInterceptor {

    private final boolean logRequestBody;
    private final boolean logResponseBody;
    private final boolean logHeaders;

    public LoggingInterceptor() {
        this(false, false, true);
    }

    public LoggingInterceptor(boolean logRequestBody, boolean logResponseBody, boolean logHeaders) {
        this.logRequestBody = logRequestBody;
        this.logResponseBody = logResponseBody;
        this.logHeaders = logHeaders;
    }

    @Override
    public void preRequest(RequestContext context) {
        StringBuilder sb = new StringBuilder();
        sb.append("发送请求: ").append(context.getMethod()).append(" ").append(context.getUrl());

        if (logHeaders && !context.getHeaders().isEmpty()) {
            sb.append("\n请求头: ");
            context.getHeaders().forEach((k, v) -> sb.append("\n  ").append(k).append(": ").append(v));
        }

        if (logRequestBody && context.getBody() != null) {
            sb.append("\n请求体: ").append(context.getBody());
        }

        log.info(sb.toString());
    }

    @Override
    public void postResponse(ResponseContext context) {
        StringBuilder sb = new StringBuilder();
        sb.append("收到响应: ").append(context.getStatusCode())
          .append(" (").append(context.getResponseTime()).append("ms)");

        if (logHeaders && context.getHeaders() != null && !context.getHeaders().isEmpty()) {
            sb.append("\n响应头: ");
            context.getHeaders().forEach((k, v) -> sb.append("\n  ").append(k).append(": ").append(v));
        }

        if (logResponseBody && context.getBody() != null) {
            String body = context.getBody();
            if (body.length() > 1000) {
                sb.append("\n响应体: ").append(body.substring(0, 1000)).append("...(truncated)");
            } else {
                sb.append("\n响应体: ").append(body);
            }
        }

        log.info(sb.toString());
    }

    @Override
    public void onError(ExceptionContext context) {
        log.error("请求失败: {} {} - {}", context.getMethod(), context.getUrl(), context.getException().getMessage());
    }
}